package com.yu8home.mq.rabbit.service;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class RabbitService {

    @RabbitListener(queues = "yu8home.aaaa")
    public void a(String message) throws InterruptedException {
        log.info("RabbitService-a：{}", message);
        Thread.sleep(1000);
    }

    @RabbitListener(queues = "yu8home.topic.bbbb")
    public void b(String message) throws InterruptedException {
        log.info("RabbitService-b：{}", message);
        Thread.sleep(1000);
    }


    @RabbitListener(queues = "yu8home.topic.cccc")
    public void c(Channel channel, @Headers Map<String, Object> headers, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Message message, String msg) throws Exception {
        log.info("RabbitService-c：deliveryTag={}，msg={}", deliveryTag, msg);

        // Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);// 手动ack

        // TODO 业务处理

        try {
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            if (message.getMessageProperties().getRedelivered()) {
                log.error("消息已重复处理失败,拒绝再次接收...");
                channel.basicReject(deliveryTag, false);
            } else {
                log.error("消息即将再次返回队列处理...");
                channel.basicNack(deliveryTag, false, true);
            }
        }

        Thread.sleep(1000);
    }


    @RabbitListener(queues = "yu8home.fanout.xxxx")
    public void x(String message) throws InterruptedException {
        log.info("RabbitService-x：{}", message);
        Thread.sleep(1000);
    }

    @RabbitListener(queues = "yu8home.fanout.yyyy")
    public void y(String message) throws Exception {
        log.info("RabbitService-y：{}", message);
        Thread.sleep(1000);
    }


    @RabbitListener(queues = "mall.order.ttl")
    public void ttl(String message) {
        log.info("RabbitService-ttl：{}", message);
    }


    @RabbitListener(queues = "mall.order.delayed")
    public void delayed(String message) {
        log.info("RabbitService-delayed：{}", message);
        // TODO 删除订单业务处理
    }

}
